import {
	useUserStore
} from "../store/user";

// api文档https://apifox.com/apidoc/shared/de49e60a-8007-4087-8d30-38b438d756a5/295008013e0 联系谈子顺

let BASE_URL = "https://m.shhegao.com";

// #ifdef H5
BASE_URL = import.meta.env.PROD ? "https://m.shhegao.com" : "/api";
// #endif

const TIME_OUT = 60000;

// 处理登录过期
const handleLoginExpired = () => {
	const userStore = useUserStore();
	// 显示提示
	uni.showToast({
		title: "登录已过期，请重新登录",
		icon: "none"
	});
	setTimeout(() => {
		// 清除用户信息
		userStore.clearLogin();
	}, 1000);
};

class Request {
	constructor(options = {}) {
		// 请求的根路径
		this.baseUrl = options.baseUrl || BASE_URL;
		// 请求的超时时间
		this.timeout = options.timeout || TIME_OUT;
	}

	requestWithoutBaseURL(options) {
		let {
			url,
			params
		} = options;
		// 拼接params到url
		if (params && typeof params === 'object') {
			const queryParams = [];
			for (const key in params) {
				queryParams.push(`${key}=${params[key]}`);
			}
			url += (url.includes('?') ? '&' : '?') + queryParams.join('&');
		}
		options.url = url;
		options.timeout = this.timeout;
		options.header = {
			...options.header,
		};
		return new Promise((resolve, reject) => {
			// 显示加载中
			// uni.showLoading({
			// 	title: "",
			// 	mask: true,
			// });
			// 开始请求
			uni.request({
				...options,
				success: (res) => {
					const {
						statusCode,
						data
					} = res;
					// 处理 HTTP 状态码
					if (statusCode !== 200) {
						uni.showToast({
							title: "服务器异常，请稍后重试",
							icon: "none"
						});
						reject(new Error("服务器异常"));
						console.log(res);
						return;
					}
					// 处理业务状态码
					if (data.status === 0 || data.code === 1) {
						resolve(data.result);
					} else if (data.code === 401) {
						handleLoginExpired();
						reject(new Error("登录已过期"));
					} else {
						uni.showToast({
							title: data.msg || "请求失败",
							icon: "none"
						});
						reject(new Error(data.msg || "请求失败"));
					}
				},
				fail: (err) => {
					uni.showToast({
						title: "网络错误，请检查网络连接",
						icon: "none"
					});
					reject(err);
				},
				complete: () => {
					// uni.hideLoading();
				},
			});
		});
	}

	request(options) {
		const {
			url
		} = options;
		options.url = this.baseUrl + url;
		options.timeout = this.timeout;
		options.header = {
			...options.header,
		};
		// console.log(options,"sadasd")
		return new Promise((resolve, reject) => {
			// 显示加载中
			// uni.showLoading({
			// 	title: "",
			// 	mask: true,
			// });
			// 开始请求
			uni.request({
				...options,
				success: (res) => {
					const {
						statusCode,
						data
					} = res;
					// 处理 HTTP 状态码
					if (statusCode !== 200) {
						uni.showToast({
							title: "服务器异常，请稍后重试",
							icon: "none"
						});
						reject(new Error("服务器异常"));
						console.log(res);
						return;
					}
					// 处理业务状态码
					if (data.code === 1) {
						resolve(data.data);
					} else if (data.code === 401) {
						handleLoginExpired();
						reject(new Error("登录已过期"));
					} else {
						setTimeout(() => {
							uni.showToast({
								title: data.msg || "请求失败",
								icon: "none",
							});
						}, 50)
						reject(new Error(data.msg || "请求失败"));
					}
				},
				fail: (err) => {
					uni.showToast({
						title: "网络错误，请检查网络连接",
						icon: "none",
					});
					reject(err);
				},
				complete: () => {
					// uni.hideLoading();
				},
			});
		});
	}

	get(url, data = {}, options = {}) {
		return this.request({
			url,
			data,
			method: "GET",
			...options,
		});
	}

	getWithoutBase(url, options = {}) {
		return this.requestWithoutBaseURL({
			url,
			...options,
			method: "GET"
		});
	}

	post(url, data = {}, options = {}) {
		return this.request({
			url,
			data,
			method: "POST",
			...options,
		});
	}

	postWithoutBase(url, data = {}, options = {}) {
		return this.requestWithoutBaseURL({
			url,
			data,
			method: "POST",
			...options,
		});
	}

	put(url, data = {}, options = {}) {
		return this.request({
			url,
			data,
			method: "PUT",
			...options,
		});
	}

	delete(url, data = {}, options = {}) {
		return this.request({
			url,
			data,
			method: "DELETE",
			...options,
		});
	}

	// 新增 upload 方法
	upload(url, data) {
		return new Promise((resolve, reject) => {
			// 显示加载中
			// uni.showLoading({
			//   title: '',
			//   mask: true
			// })

			// 开始上传文件
			uni.uploadFile({
				url: this.baseUrl + url,
				...data,
				success: (res) => {
					const {
						statusCode,
						data
					} = res;

					// 处理 HTTP 状态码
					if (statusCode !== 200) {
						uni.showToast({
							title: "服务器异常，请稍后重试",
							icon: "none",
						});
						reject(new Error("服务器异常"));
						return;
					}

					// 解析返回数据
					let parsedData;
					try {
						parsedData = JSON.parse(data);
					} catch (e) {
						console.error("解析上传响应失败", e);
						reject(new Error("解析上传响应失败"));
						return;
					}

					// 处理业务状态码
					if (parsedData.code === 1) {
						resolve(parsedData.data);
					} else if (parsedData.code === 401) {
						handleLoginExpired();
						reject(new Error("登录已过期"));
					} else {
						uni.showToast({
							title: parsedData.msg || "上传失败",
							icon: "none",
						});
						reject(new Error(parsedData.msg || "上传失败"));
					}
				},
				fail: (err) => {
					uni.showToast({
						title: "网络错误，请检查网络连接",
						icon: "none",
					});
					reject(err);
				},
				complete: () => {
					// uni.hideLoading();
				},
			});
		});
	}
}

// 创建请求实例
const request = new Request();

// 请求拦截器
uni.addInterceptor("request", {
	invoke(args) {
		// 请求前添加token等通用header
		const userStore = useUserStore();
		const token = userStore?.token;
		let type=args.header["content-type"]
		if(!type){
			type="application/x-www-form-urlencoded"
		}
		args.header = {
			...args.header,
			"content-type":type,
			token: token || "",
		};
		return args;
	},
});

export default request;